package org.abettor.octopus.worker;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import org.abettor.octopus.data.AuthenticationList;
import org.abettor.octopus.data.AuthenticationPair;
import org.abettor.octopus.ui.proxy.MainDialogProxy;

/**
 * 密码破解线程
 * @author abettor
 *
 */
public class Cracker extends Thread
{
	private boolean stopSignal = false;
	private boolean active = false;
	private String url;
	private AuthenticationList authList;
	private MainDialogProxy proxy;

	/**
	 * 默认构造函数
	 *
	 */
	public Cracker()
	{
		super();
	}

	/**
	 * 带参数的构造函数
	 * @param proxy 主窗口行为代理对象
	 * @param url 要破解的数据库连接字符串
	 * @param authList 用于破解的备选用户验证信息列表
	 */
	public Cracker(MainDialogProxy proxy, String url, AuthenticationList authList)
	{
		this.proxy = proxy;
		this.url = url;
		this.authList = authList;
	}

	/**
	 * @see java.lang.Thread#start()
	 */
	public void start()
	{
		stopSignal = false;
		super.start();
	}

	/**
	 * 停止破解线程
	 * @see java.lang.Thread#stop()
	 */
	public void end()
	{
		stopSignal = true;
	}

	/**
	 * @see java.lang.Thread#run()
	 */
	public void run()
	{
		if(authList == null)
		{
			active = false;
			return;
		}

		active = true;
		while(! stopSignal)
		{
			AuthenticationPair authPair = authList.popFront();
			if(authPair == null)
			{
				break;
			}

			try
			{
				Connection conn = DriverManager.getConnection(url, authPair.getUserName(), authPair.getPassword());
				if(conn != null)
				{
					conn.close();
					conn = null;

					//	连接信息写入前台界面
					proxy.addToResultTable(authPair.getUserName(), authPair.getPassword());
				}
			}
			catch(SQLException e)
			{
				//e.printStackTrace();
				continue;
			}
		}

		active = false;
	}

	/**
	 * 检查当前线程对象是否已经终止运行
	 */
	public boolean isActive()
	{
		return active;
	}

	/**
	 * 设置身份验证信息列表
	 * @param authList 身份验证信息列表对象
	 */
	public void setAuthList(AuthenticationList authList)
	{
		this.authList = authList;
	}

	/**
	 * 设置数据库连接字符串
	 * @param url 数据库连接字符串
	 */
	public void setURL(String url)
	{
		this.url = url;
	}
}
